package com.zj.androidcamera.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Face;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Size;
import android.widget.ImageView;

public class FaceView extends ImageView {
    private static final String TAG = "FaceView";
    private Context mContext;
    private Paint mLinePaint;
    private Face[] mFaces;
    private Matrix mMatrix = new Matrix();
    private RectF mRect = new RectF();

    // 相机操作
    private com.zj.util.CameraUtil cameraUtil = com.zj.util.CameraUtil.getInstance();

    public FaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        initPaint();
        mContext = context;
    }


    public void setFaces(Face[] faces) {
        this.mFaces = faces;
        invalidate();
    }

    public void clearFaces() {
        mFaces = null;
        invalidate();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        if (mFaces == null || mFaces.length < 1) {
            return;
        }
        boolean isMirror = false;
        int Id = cameraUtil.getCameraId();
        if (Id == CameraInfo.CAMERA_FACING_BACK) {
            isMirror = false; //后置Camera无需mirror
        } else if (Id == CameraInfo.CAMERA_FACING_FRONT) {
            isMirror = true;  //前置Camera需要mirror
        }
        com.zj.util.CameraUtil.prepareMatrix(mMatrix, isMirror, 90, getWidth(), getHeight());
        Log.e(TAG, "onDraw: width = " + getWidth() + " height = " + getHeight());
        canvas.save();
        mMatrix.postRotate(0); //Matrix.postRotate默认是顺时针
        canvas.rotate(-0);   //Canvas.rotate()默认是逆时针
        for (int i = 0; i < mFaces.length; i++) {
            mRect.set(mFaces[i].rect);
            Log.e(TAG, "onDraw: " + mFaces[i].rect);
            mMatrix.mapRect(mRect);
            canvas.drawRect(mRect, mLinePaint);
            Log.e(TAG, "onDraw: " + mRect.toString());
        }
        canvas.restore();
        super.onDraw(canvas);
    }

    private void initPaint() {
        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//		int color = Color.rgb(0, 150, 255);
        int color = Color.rgb(98, 212, 68);
//		mLinePaint.setColor(Color.RED);
        mLinePaint.setColor(color);
        mLinePaint.setStyle(Style.STROKE);
        mLinePaint.setStrokeWidth(5f);
        mLinePaint.setAlpha(180);
    }

    public Size getViewSize() {
        return new Size(getWidth(), getHeight());
    }
}
